import Access from '@/components/Access';
import type { ActionType, ProColumns, ProFormInstance } from '@/components/Pro/';
import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@/components/Pro/';
// import { CHARGING_PILE_TYPE } from '@/dictionary';
import {
  deviceManagerControllerAdd as add,
  deviceManagerControllerBatchDelete as batchDelete,
  deviceManagerControllerBatchEnOrDisableDevices as batchDisabled,
  deviceManagerControllerDeviceList as getList,
  deviceManagerControllerEdit as edit,
  deviceManagerControllerUploadPic as uploadPic,
} from '@/services/ess/deviceManager';
import { getGlobalHandleTip } from '@/utils';
import { getIntl } from '@umijs/max';
import type { UploadFile, UploadProps } from 'antd';
import { Image, message, Modal, Space, Switch, Upload } from 'antd';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { useAccess, useIntl, useModel } from 'umi';

// const CURREN_DEVICE_TYPE = 4;

const { confirm } = Modal;

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.DeviceManagerReq) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res.success) {
      getGlobalHandleTip('ADD');
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.addFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.DeviceManagerInfoVo) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      getGlobalHandleTip('EDIT');
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.editFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.DeviceManagerInfoVo[]) => {
  if (!selectedRows) return true;
  try {
    const res = await batchDelete(selectedRows.map((row) => row.id));
    if (res.success) {
      getGlobalHandleTip('DEL');
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.delFailedTips' }));
    return false;
  }
};

interface TableProps {
  deveiceType?: number;
  titleName?: string;
}

const Table = forwardRef((props: TableProps, ref: any) => {
  const { deveiceType: CURREN_DEVICE_TYPE, titleName } = props;
  const access = useAccess();
  const { stationId } = useModel('@@initialState')?.initialState || {};

  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const modalFormRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<API.DeviceManagerInfoVo>({});
  const [selectedRowsState, setSelectedRows] = useState<API.DeviceManagerInfoVo[]>([]);
  const [readonly, setReadonly] = useState(false);
  const [deleteDisabled, setDeleteDisabled] = useState(false);
  const [imgUrl, setImgUrl] = useState(undefined);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const intl = useIntl();

  const CHARGING_PILE_TYPE = {
    1: {
      text: intl.formatMessage({ id: 'systemManagement.supplementary.DC' }),
    },
    2: {
      text: intl.formatMessage({ id: 'systemManagement.supplementary.AC' }),
    },
  };

  const DEVICE_TYPE = {
    3: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.pcs',
      }),
      order: 1,
    },
    1: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.Batterycabinet',
      }),
      order: 2,
    },
    2: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.Batteryboxs',
      }),
      order: 3,
    },
    10: {
      text: intl.formatMessage({ id: 'systemManagement.supplementary.chargingStation' }),
      order: 3,
    },
  };

  const deleteRow = (rows: API.DeviceManagerInfoVo[] = selectedRowsState) => {
    if (rows?.length < 1) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }

    if (deleteDisabled) return;
    setDeleteDisabled(true);

    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: intl.formatMessage({ id: 'global.delTip' }),
      onOk: async () => {
        const res = await handleRemove(rows);
        if (res) {
          setSelectedRows([]);
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDeleteDisabled(false);
      },
    });
  };

  useImperativeHandle(ref, () => ({
    add: () => {
      setImgUrl(undefined);
      setFileList([]);
      setReadonly(false);
      setCurrentRow({});
      handleModalOpen(true);
    },
    delete: () => {
      deleteRow();
    },
  }));

  const onRemove: UploadProps['onRemove'] = () => {
    setFileList([]);
    setImgUrl(undefined);
  };

  const handlePreview = async () => {
    setPreviewOpen(true);
  };

  const uploadImg: UploadProps = {
    name: 'file',
    listType: 'picture-card',
    fileList: fileList,
    onRemove: onRemove,
    onPreview: handlePreview,
    maxCount: 1,
    accept: 'image/png, image/jpeg, image/jpg',
    multiple: false,
    customRequest: async (info) => {
      console.log('info', info);
      const isLt5M = info.file?.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error(intl.formatMessage({ id: 'systemManagement.neddTochange.imgMax' }));
        return;
      }
      const res = await uploadPic({
        attr: info.file,
      });
      if (res?.success) {
        const url = res?.data?.device;
        setImgUrl(url);
        setFileList([{ ...info.file, url, status: 'done' }]);
        message.success(
          `${info.file.name} ${intl.formatMessage({
            id: 'systemManagement.neddTochange.imageUploadSuccess',
          })}`,
        );
        return info.file;
      }
      const msg = info?.file?.response?.message;
      message.error(
        `${info.file.name} ${intl.formatMessage({
          id: 'systemManagement.neddTochange.imageUploadFailed',
        })}  ${msg ? ',' + msg : ''}`,
      );
    },
  };

  const handleColNum = access.calcPermsLen([
    'sys:device:edit',
    'sys:device:detail',
    'sys:device:del',
  ]);

  const columns: ProColumns<API.DeviceManagerInfoVo>[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      dataIndex: 'pageIndex',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.Factory' }),
      dataIndex: 'manufacturer',
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.DeviceType' }),
      dataIndex: 'deviceType',
      valueEnum: DEVICE_TYPE,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.Devicemodel' }),
      dataIndex: 'deviceModel',
      order: 1,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.status' }),
      dataIndex: 'status',
      valueEnum: {
        true: {
          text: intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' }),
        },
        false: {
          text: intl.formatMessage({ id: 'systemManagement.generalProcedure.disable' }),
        },
      },
      hideInTable: !access.can('sys:device:setStatus'),
      render: (_, record) => (
        <Switch
          checkedChildren={intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' })}
          unCheckedChildren={intl.formatMessage({
            id: 'systemManagement.generalProcedure.disable',
          })}
          checked={Boolean(record.status)}
          onChange={(checked) => {
            confirm({
              title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
              content: checked
                ? intl.formatMessage({ id: 'systemManagement.neddTochange.confirmEnableSelected' })
                : intl.formatMessage({
                    id: 'systemManagement.neddTochange.confirmDisableSelected',
                  }),
              onOk: async () => {
                const res = await batchDisabled({
                  deviceIds: [record.id],
                  status: checked,
                });
                if (res?.success) {
                  getGlobalHandleTip('ENABLE');
                  actionRef.current?.reloadAndRest?.();
                }
              },
            });
          }}
        />
      ),
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.type' }),
      dataIndex: 'cpType',
      valueEnum: CHARGING_PILE_TYPE,
      hideInSearch: true,
      width: 90,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.supplementary.ratedInputVoltage' }),
      dataIndex: 'ratedInVol',
      render: (_, record) => record.ratedInVol + 'V',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.supplementary.ratedInputCurrent' }),
      dataIndex: 'ratedInCurr',
      render: (_, record) => record.ratedInCurr + 'A',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.supplementary.ratedOutputVoltage' }),
      dataIndex: 'ratedOutVol',
      render: (_, record) => record.ratedOutVol + 'V',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.supplementary.ratedOutputCurrent' }),
      dataIndex: 'ratedOutCurr',
      render: (_, record) => record.ratedOutCurr + 'V',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.supplementary.outputFrequency' }),
      dataIndex: 'outFreq',
      render: (_, record) => record.outFreq + 'Hz',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.supplementary.ratedOutputPower' }),
      dataIndex: 'ratedOutPower',
      render: (_, record) => record.ratedOutPower + 'kW',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      hideInTable: handleColNum === 0,
      width: handleColNum * 60,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Access perm="sys:device:edit" key="edit">
            <a
              key="edit"
              onClick={() => {
                setReadonly(false);
                handleModalOpen(true);
                const url = record.pictureDir;
                const file = {
                  uid: '-1',
                  name: url,
                  status: 'done',
                  url: url,
                };
                setImgUrl(url);
                setFileList([file]);
                console.log('我是编辑穿过', record);

                setCurrentRow({
                  ...record,
                  pictureDir: {
                    file: file,
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
            </a>
          </Access>
          <Access perm="sys:device:detail" key="detail">
            <a
              key="detail"
              onClick={() => {
                setReadonly(true);
                handleModalOpen(true);
                const url = record.pictureDir;
                const file = {
                  uid: '-1',
                  name: url,
                  status: 'done',
                  url: url,
                };
                setImgUrl(url);
                setFileList([file]);
                setCurrentRow({
                  ...record,
                  pictureDir: {
                    file: file,
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.detail' })}
            </a>
          </Access>
          <Access perm="sys:device:del" key="del">
            <a key="delete" className="global-del-color" onClick={() => deleteRow([record])}>
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
            </a>
          </Access>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <ProTable<API.DeviceManagerInfoVo, API.PageParams>
        actionRef={actionRef}
        formRef={formRef}
        rowKey="id"
        params={{ stationId, deviceType: CURREN_DEVICE_TYPE }}
        request={getList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        toolBarRender={() => []}
        customToolBarClass="global-tabs-custom-tools"
      />
      <ModalForm
        formRef={modalFormRef}
        modalProps={{
          destroyOnClose: true,
        }}
        initialValues={{
          status: true,
          ...currentRow,
          cpType: currentRow?.cpType ? currentRow?.cpType?.toString() : '1',
        }}
        submitter={{
          render: (_, doms) => !readonly && <Space>{doms}</Space>,
        }}
        title={
          currentRow?.id
            ? `${
                readonly
                  ? intl.formatMessage({ id: 'systemManagement.generalProcedure.view' })
                  : intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })
              } ${titleName}`
            : `${intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })} ${titleName}`
        }
        readonly={currentRow?.id && readonly}
        layout="horizontal"
        width={650}
        colProps={{ xs: 12 }}
        labelCol={{
          flex: `0 0 110px`,
        }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          let success;
          value.pictureDir = imgUrl;
          value.stationId = stationId;
          value.deviceType = CURREN_DEVICE_TYPE;
          if (currentRow?.id) {
            success = await handleEdit({ ...currentRow, ...value } as API.DeviceManagerInfoVo);
          } else {
            success = await handleAdd(value as API.DeviceManagerInfoVo);
          }
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          name="deviceModel"
          label={intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.Devicemodel' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.deviceModel' }),
            },
          ]}
          fieldProps={{
            maxLength: 30,
          }}
        />
        <ProFormText
          name="manufacturer"
          label={intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.Factory' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.manufacturer' }),
            },
          ]}
          fieldProps={{
            maxLength: 30,
          }}
        />
        <ProFormRadio.Group
          label={intl.formatMessage({ id: 'systemManagement.supplementary.Typeofchargingpile' })}
          name="cpType"
          options={[
            {
              label: intl.formatMessage({ id: 'systemManagement.supplementary.DC' }),
              value: '1',
            },
            {
              label: intl.formatMessage({ id: 'systemManagement.supplementary.AC' }),
              value: '2',
            },
          ]}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.neddTochange.chargingPileTypeRequired',
              }),
            },
          ]}
        />
        <ProFormRadio.Group
          label={intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.status' })}
          name="status"
          options={[
            {
              label: intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' }),
              value: true,
            },
            {
              label: intl.formatMessage({ id: 'systemManagement.generalProcedure.disable' }),
              value: false,
            },
          ]}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.status' }),
            },
          ]}
        />
        <ProFormDigit
          name="ratedInVol"
          label={intl.formatMessage({ id: 'systemManagement.supplementary.ratedInputVoltage' })}
          max={1000000000}
          // addonAfter={readonly ? 'kW' : undefined}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.neddTochange.ratedInputVoltageRequired',
              }),
            },
          ]}
        />
        <ProFormDigit
          name="ratedOutVol"
          label={intl.formatMessage({ id: 'systemManagement.supplementary.ratedOutputVoltage' })}
          max={1000000000}
          // addonAfter={readonly ? 'kW' : undefined}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.neddTochange.ratedOutputVoltageRequired',
              }),
            },
          ]}
        />
        <ProFormDigit
          name="ratedInCurr"
          label={intl.formatMessage({ id: 'systemManagement.supplementary.ratedInputCurrent' })}
          max={1000000000}
          // addonAfter={readonly ? 'kW' : undefined}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.neddTochange.ratedInputVoltageRequired',
              }),
            },
          ]}
        />
        <ProFormDigit
          name="ratedOutCurr"
          label={intl.formatMessage({ id: 'systemManagement.supplementary.ratedOutputCurrent' })}
          max={1000000000}
          // addonAfter={readonly ? 'kW' : undefined}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.neddTochange.ratedInputCurrentRequired',
              }),
            },
          ]}
        />

        <ProFormDigit
          name="outFreq"
          label={intl.formatMessage({ id: 'systemManagement.supplementary.outputFrequency' })}
          max={1000000000}
          // addonAfter={readonly ? 'kW' : undefined}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.neddTochange.ratedOutputCurrentRequired',
              }),
            },
          ]}
        />
        <ProFormDigit
          name="ratedOutPower"
          label={intl.formatMessage({ id: 'systemManagement.supplementary.ratedOutputPower' })}
          max={1000000000}
          // addonAfter={readonly ? 'kW' : undefined}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.neddTochange.ratedOutputPowerRequired',
              }),
            },
          ]}
        />

        <ProForm.Item
          name="pictureDir"
          label={intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.deviceImages' })}
          style={{ width: '100%' }}
          tooltip={intl.formatMessage({ id: 'systemManagement.neddTochange.imageFormatSupport' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.deviceImage' }),
            },
            () => ({
              validator(_, value) {
                if (!value) {
                  return Promise.resolve();
                }
                if (value?.file?.status === 'done' || value?.file?.status === 'uploading') {
                  return Promise.resolve();
                }
                return Promise.reject(
                  intl.formatMessage({ id: 'systemManagement.requiredFields.deviceImage' }),
                );
              },
            }),
          ]}
        >
          <Upload {...uploadImg} disabled={readonly}>
            {fileList.length < 1 &&
              intl.formatMessage({ id: 'systemManagement.generalProcedure.upload' })}
          </Upload>
        </ProForm.Item>
        <ProFormTextArea
          colProps={{ md: 24 }}
          label={intl.formatMessage({ id: 'systemManagement.userManagement.remarksDescription' })}
          name="remark"
          fieldProps={{
            maxLength: 150,
          }}
        />
      </ModalForm>
      {imgUrl && (
        <Image
          wrapperStyle={{ display: 'none' }}
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => setPreviewOpen(visible),
          }}
          src={imgUrl}
        />
      )}
    </div>
  );
});

export default Table;
